<template>
  <div class="add-room-page">
    <van-nav-bar safe-area-inset-top title="修改房源信息" left-arrow @click-left="onClickLeft" />
    <div class="top-info">填写房屋信息(附<span class="dot">*</span>为必填信息)</div>
    <div class="form-box">
      <van-form @submit="onSubmit">
        <van-field
          v-model="formData.introduce"
          name="introduce"
          rows="2"
          autosize
          label="房屋描述"
          type="textarea"
          placeholder="请输入房屋描述"
          label-align="top"
          maxlength="40"
          clearable
          required
          show-word-limit
          :rules="[{ required: true, message: '请填写房屋描述' }]"
        />

        <!-- 房间图片 -->
        <van-field
          name="pictureUrl"
          label="房间图片"
          label-align="top"
          required
          :rules="[{ required: true, message: '请上传至少一张房间图片' }]"
        >
          <template #input>
            <van-uploader
              @delete="handledelete"
              :after-read="fileAfterread"
              v-model="formData.pictureUrl"
              multiple
              :max-count="10"
            />
          </template>
        </van-field>

        <van-field name="video" label="房间视频" label-align="top">
          <template #input>
            <van-uploader accept="video/*" :after-read="videoUpload" v-model="formData.video" reupload max-count="1">
              <template #preview-cover="{ objectUrl }">
                <video class="room-video" ref="videoTag" @click="videoPreview(objectUrl, formData.video)">
                  <source :src="objectUrl" />
                </video>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <!-- 预览视频 -->
        <van-popup
          v-model:show="previewVideo"
          closeable
          class="preview-video-popup"
          :style="{ width: '100%', height: '100%' }"
        >
          <div class="preview-video-box">
            <video class="video-view" :src="previewVideoURL" autoplay controls="controls" muted></video>
          </div>
        </van-popup>

        <van-field
          v-model="formData.location"
          is-link
          readonly
          required
          name="location"
          label="房屋位置"
          placeholder="点击选择房屋位置"
          @click="showArea = true"
          :rules="[{ required: true, message: '请选择房屋位置' }]"
        />
        <van-popup v-model:show="showArea" position="bottom">
          <van-area v-model="formData.areaCode" :area-list="areaList" @confirm="onConfirm" @cancel="showArea = false" />
        </van-popup>

        <van-field
          v-model="formData.address"
          name="address"
          rows="2"
          autosize
          label="详细地址（街、巷、里、路号）"
          type="textarea"
          placeholder="请输入详细的地址"
          label-align="top"
          maxlength="25"
          clearable
          required
          show-word-limit
          :rules="[{ required: true, message: '请输入详细的地址' }]"
        />

        <van-field
          v-model="formData.subwayName"
          is-link
          readonly
          label="地铁线路"
          placeholder="请选择，没有可以不填"
          @click="subwayNamePicker = true"
          name="subwayName"
        />

        <van-popup v-model:show="subwayNamePicker" round position="bottom" title="选择地铁线路">
          <van-picker
            v-model="formData.subwayNameArr"
            :columns-field-names="customFieldName"
            :columns="guangzhouSubwayLines"
            @cancel="subwayNamePicker = false"
            @confirm="subwayNamConfirm"
          />
        </van-popup>

        <van-field name="elevator" required label="电梯" :rules="[{ required: true, message: '请选择' }]">
          <template #input>
            <van-radio-group v-model="formData.elevator" direction="horizontal">
              <van-radio name="1">有</van-radio>
              <van-radio name="2">无</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="type" required label="房屋类型" :rules="[{ required: true, message: '请选择' }]">
          <template #input>
            <van-radio-group v-model="formData.type" direction="horizontal">
              <van-radio name="公寓">公寓</van-radio>
              <van-radio name="城中村">城中村</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="network" required label="网络" :rules="[{ required: true, message: '请选择' }]">
          <template #input>
            <van-radio-group v-model="formData.network" direction="horizontal">
              <van-radio name="1">有</van-radio>
              <van-radio name="2">无</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field
          required
          v-model="formData.area"
          placeholder="请输入面积"
          name="area"
          type="digit"
          maxlength="3"
          label="面积"
          :rules="[{ required: true, message: '请输入面积' }]"
        >
          <template #right-icon>平方</template>
        </van-field>

        <van-field name="hight" label="楼层高度" required :rules="[{ required: true, message: '请输入楼层高度' }]">
          <template #input>
            <van-stepper v-model="formData.hight" />
          </template>
        </van-field>

        <van-field
          v-model="formData.houseNum"
          is-link
          readonly
          name="houseNum"
          label="户型"
          placeholder="点击选择户型"
          :rules="[{ required: true, message: '请选择户型' }]"
          @click="houseNumPicker = true"
          required
        />
        <van-popup v-model:show="houseNumPicker" position="bottom">
          <van-picker
            v-model="formData.houseNumArr"
            :columns="houseNumEnume"
            @confirm="houseNumConfirm"
            @cancel="houseNumPicker = false"
          />
        </van-popup>

        <van-field
          required
          v-model="formData.price"
          placeholder="请输入租金"
          name="price"
          type="number"
          maxlength="4"
          label="房屋租金"
          :rules="[{ required: true, message: '请输入租金' }]"
        >
          <template #right-icon>元/月</template>
        </van-field>

        <van-field
          v-model="formData.detain"
          is-link
          readonly
          name="detain"
          label="押金方式"
          placeholder="请选择押金方式"
          @click="detainPicker = true"
          required
          :rules="[{ required: true, message: '请选择押金方式' }]"
        />
        <van-popup v-model:show="detainPicker" position="bottom">
          <van-picker
            v-model="formData.detainArr"
            :columns="detainEnv"
            @confirm="detainPickerConfirm"
            @cancel="detainPicker = false"
          />
        </van-popup>

        <van-field
          v-model="formData.waterRate"
          placeholder="请输入水费"
          name="waterRate"
          type="number"
          maxlength="4"
          label="水费"
          :rules="[{ required: false, message: '请输入水费' }]"
        >
          <template #right-icon>元/吨</template>
        </van-field>

        <van-field
          v-model="formData.electricRate"
          placeholder="请输入电费"
          name="electricRate"
          type="number"
          maxlength="4"
          label="电费"
          :rules="[{ required: false, message: '请输入电费' }]"
        >
          <template #right-icon>元/度</template>
        </van-field>

        <van-field
          v-model="formData.manageRate"
          placeholder="请输入管理费"
          name="manageRate"
          type="number"
          maxlength="4"
          label="管理费"
        >
          <template #right-icon>元/月</template>
        </van-field>

        <div style="padding: 16px; background-color: #fff">
          <van-button :loading="btnLoading" round block type="primary" native-type="submit"> 提交 </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { areaList } from '@vant/area-data';
import { showFailToast, showSuccessToast } from 'vant';

import { houseNumEnume, detainEnv } from '@/constants/guangzhou.js';

import { getSubwayLines, PostUploadFile, houseModify, requesRoomDetails } from '@/api';

import { modifyStationsData } from '@/tools';

const router = useRouter();
const route = useRoute();

function onClickLeft() {
  router.back();
}

onMounted(() => {
  //获取广州市地铁线路图
  handleGetSubwayLines();
  //表单回显
  SetFormData();
});

const guangzhouSubwayLines = ref([]);

const customFieldName = ref({
  text: 'lineName',
  value: 'lineId',
  children: 'stations',
});

async function handleGetSubwayLines() {
  let SubwayLines = JSON.parse(window.sessionStorage.getItem('SubwayLines'));
  if (SubwayLines) {
    guangzhouSubwayLines.value = modifyStationsData(SubwayLines);
    return;
  } else {
    try {
      let res = await getSubwayLines();
      guangzhouSubwayLines.value = modifyStationsData(res.businessObject);
      window.sessionStorage.setItem('SubwayLines', JSON.stringify(res.businessObject));
    } catch (error) {
      console.log(error);
    }
  }
}
let formData = reactive({
  introduce: '',
  pictureUrl: [],
  video: [],
  location: '',
  address: '',
  areaCode: '',
  elevator: '',
  type: '',
  network: '',
  subwayName: '',
  subwayNameArr: [],
  area: '',
  hight: '',
  houseNum: '',
  houseNumArr: [],
  price: '',
  detain: '',
  detainArr: [],
  waterRate: '',
  electricRate: '',
  manageRate: '',
});

// 提交前，转换表单数据格式
function dataTranslation(values) {
  try {
    let newVal = Object.assign(
      { ...values },
      {
        detain: formData?.detainArr[0],
        houseNum: formData?.houseNumArr[0],
        pictureUrl: pictureArray.value,
        coverUrl: pictureArray?.value[0],
        video: formData?.video[0]?.url,
        areaCode: formData.areaCode,
        subwayNameArr: formData.subwayNameArr,
        subwayName: formData.subwayName?.split('-')[1],
        subwayNum: formData.subwayName?.split('-')[0],
        houseNumArr: formData.houseNumArr,
        detainArr: formData.detainArr,
      }
    );
    return newVal;
  } catch (error) {
    console.log(error);
    showFailToast('系统未知错误，请把表单填写完整');
  }
}

// 表单回显数据
async function SetFormData() {
  try {
    const { id } = route.query;
    let { data } = await requesRoomDetails({ id });
    for (const key in data) {
      const element = data[key];
      if (!Array.isArray(formData[key])) {
        formData[key] = element;
      }
    }
    formData.video = [{ url: data.video }];
    formData.pictureUrl = data.pictureUrl.map(item => {
      return {
        url: item,
        isImage: true,
      };
    });
    pictureArray.value = data.pictureUrl;
    if (Array.isArray(data.subwayNameArr)) {
      const firstItemAsNumber = Number(data.subwayNameArr[0]);
      const newArray = [firstItemAsNumber, data.subwayNameArr[1]];
      formData.subwayNameArr = newArray || [];
    }
    formData.subwayName = `${data.subwayNum}-${data.subwayName}`;
    formData.houseNumArr = data.houseNumArr || [];
    formData.houseNum = data.houseNumDescription;
    formData.detain = detainEnv.find(item => item.value == data.detain)?.text;
    formData.detainArr = data.detainArr || [];
  } catch (error) {
    console.log(error);
  }
}

let pictureArray = ref([]);
let showArea = ref(false);
let houseNumPicker = ref(false);
let detainPicker = ref(false);
let subwayNamePicker = ref(false);

const onConfirm = ({ selectedOptions }) => {
  showArea.value = false;
  formData.location = selectedOptions.map(item => item.text).join('/');
};
function houseNumConfirm({ selectedOptions }) {
  formData.houseNum = selectedOptions[0]?.text;
  houseNumPicker.value = false;
}
function detainPickerConfirm({ selectedOptions }) {
  formData.detain = selectedOptions[0]?.text;
  detainPicker.value = false;
}
function subwayNamConfirm({ selectedOptions }) {
  subwayNamePicker.value = false;
  formData.subwayName = selectedOptions.map(item => item.lineName).join('-');
}

//图片上传
function fileAfterread(params) {
  params.status = 'uploading';
  params.message = '上传中...';
  PostUploadFile(params.file)
    .then(res => {
      params.status = '';
      params.message = '上传完成';
      pictureArray.value.push(res.msg);
    })
    .catch(err => {
      console.log(err);
      params.status = 'failed';
      params.message = '上传失败';
    });
}
// 视频上传
function videoUpload(params) {
  params.status = 'uploading';
  params.message = '上传中...';
  PostUploadFile(params.file)
    .then(res => {
      params.status = '';
      params.message = '上传完成';
      formData.video[0].url = res.msg;
    })
    .catch(err => {
      console.log(err);
      params.status = 'failed';
      params.message = '上传失败';
    });
}

// 图片删除
function handledelete(val, { index }) {
  pictureArray.value.splice(index, 1);
}

let btnLoading = ref(false);
// 提交表单
const onSubmit = async values => {
  try {
    const { id } = route.query;
    let postData = dataTranslation({ ...values, id });
    btnLoading.value = true;
    let res = await houseModify(postData);
    if (res.msg) {
      btnLoading.value = false;
      showSuccessToast('修改成功');
      router.push('/nav/home');
    }
  } catch (error) {
    console.log(error);
    showFailToast('提交失败，请检查填写是否正确');
    btnLoading.value = false;
  }
};

let previewVideo = ref(false);
let previewVideoURL = ref('');

function videoPreview(file, videoURL) {
  if (videoURL[0]) {
    previewVideoURL.value = videoURL[0].url;
  } else {
    previewVideoURL.value = file;
  }
  previewVideo.value = true;
}
</script>

<style lang="less" scoped>
.add-room-page {
  background-color: #ececec;
  width: 100%;

  .top-info {
    padding: 0 12px;
    width: 100%;
    height: 40px;
    font-size: 13px;
    display: flex;
    align-items: center;

    .dot {
      color: red;
      font-size: 16px;
    }
  }

  .form-box {
    .uploade-img {
      width: 100%;
      background-color: #fff;
      padding: 24px 12px;
    }

    .room-video {
      width: 100%;
    }

    :deep(.preview-video-popup) {
      max-width: inherit;
    }

    .preview-video-box {
      width: 100%;
      height: 100%;
      background-color: transparent;

      .video-view {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background-color: #000;
      }
    }
  }
}
</style>
